#include "ThreadCond.h"
#include <thread>
#include <chrono>

void ThreadCond::Wait()
{
    std::unique_lock<std::mutex> lck(m_cvMutex);
    m_cond.wait(lck);
}

bool ThreadCond::WaitForTimeMS(unsigned int timeOutMS)
{
    std::unique_lock<std::mutex> lck(m_cvMutex);
    auto ret = m_cond.wait_for(lck, std::chrono::milliseconds(timeOutMS));
    if (ret == std::cv_status::no_timeout) {
        return true;
    } else {
        return false;
    }
}

bool ThreadCond::WaitForTimeS(unsigned int timeOutS)
{
    std::unique_lock<std::mutex> lck(m_cvMutex);
    auto ret = m_cond.wait_for(lck, std::chrono::seconds(timeOutS));
    if (ret == std::cv_status::no_timeout) {
        return true;
    } else {
        return false;
    }
}

void ThreadCond::NotifyOne()
{
    m_cond.notify_one();
}

void ThreadCond::NotifyAll()
{
    m_cond.notify_all();
}


/**
 * @brief 等待条件变量
 * 
 * @param timeOutMS 等待时间为毫秒
 * @return true 
 * @return false 
 */
bool ThreadCond::WaitForVariable(unsigned int timeOutMS)
{
    std::unique_lock<std::mutex> lck(m_cvMutex);

    auto ret = m_cond.wait_for(lck, 
                               std::chrono::milliseconds(timeOutMS), 
                               [this]{return m_variable;});
 
    return ret;
}

void ThreadCond::NotifyForVariable()
{
    m_variable = true;
    m_cond.notify_all();
}

void ThreadCond::ResetForVariable()
{
    m_variable = false;
}